import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useAppStore = defineStore('app', () => {
  // 状态
  const isDarkMode = ref(false)
  const sidebarCollapsed = ref(false)
  const loading = ref(false)

  // 方法
  const toggleDarkMode = () => {
    isDarkMode.value = !isDarkMode.value
    document.documentElement.classList.toggle('dark', isDarkMode.value)

    // 保存到localStorage
    localStorage.setItem('darkMode', isDarkMode.value.toString())
  }

  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value
    localStorage.setItem('sidebarCollapsed', sidebarCollapsed.value.toString())
  }

  const setLoading = (state) => {
    loading.value = state
  }

  const initializeTheme = () => {
    // 从localStorage恢复设置
    const savedDarkMode = localStorage.getItem('darkMode')
    const savedSidebarCollapsed = localStorage.getItem('sidebarCollapsed')

    if (savedDarkMode !== null) {
      isDarkMode.value = savedDarkMode === 'true'
      document.documentElement.classList.toggle('dark', isDarkMode.value)
    }

    if (savedSidebarCollapsed !== null) {
      sidebarCollapsed.value = savedSidebarCollapsed === 'true'
    }
  }

  return {
    // 状态
    isDarkMode,
    sidebarCollapsed,
    loading,

    // 方法
    toggleDarkMode,
    toggleSidebar,
    setLoading,
    initializeTheme
  }
})